// pages/login/login.js
const app = getApp()
const { request } = require("../../utils/request")

Page({
  data: {
    phone: "",
    password: "",
  },

  // 处理手机号输入
  handlePhoneInput(e) {
    this.setData({
      phone: e.detail.value,
    })
  },

  // 处理密码输入
  handlePasswordInput(e) {
    this.setData({
      password: e.detail.value,
    })
  },
  // 处理注册请求
  handleRegister() {
    wx.navigateTo({
      url: "/pages/questionnaire/questionnaire",
      success: () => {
        console.log("跳转成功")
      },
      fail: (err) => {
        console.error("跳转失败:", err)
      },
    })
  },
  // 处理登录请求
  handleLogin() {
    const { phone, password } = this.data

    // 简单的输入验证
    if (!phone || !password) {
      wx.showToast({
        title: "请填写完整信息",
        icon: "none",
      })
      return
    }

    // 发送登录请求
    request({
      url: `${app.globalData.baseUrl}/login?phone=${phone}&password=${password}`,
      method: "POST",
    })
      .then((res) => {
        console.log("登录响应:", res.data)
        if (res.data.code == 0) {
          wx.showToast({ title: res.data.msg, icon: "none" })
        }
        if (res.data.code == 1) {
          console.log("登录成功")
          // 保存登录信息到本地存储
          const loginData = res.data.data
          wx.setStorageSync("userId", loginData.id)
          wx.setStorageSync("tokenName", loginData.tokenName)
          wx.setStorageSync("token", loginData.token)
          const tokenName = loginData.tokenName
          if (tokenName === "usertoken") {
            wx.setStorageSync("urlPath", "employee")
          } else if (tokenName === "admintoken") {
            wx.setStorageSync("urlPath", "admin")
          } else {
            wx.setStorageSync("urlPath", "sadmin")
          }
          if (wx.getStorageSync("urlPath") === "admin" || wx.getStorageSync("urlPath") === "employee") {
            wx.switchTab({
              url: "/pages/shop/shop",
              success: () => {
                console.log("跳转成功")
              },
              fail: (err) => {
                console.error("跳转失败:", err)
              },
            })
          } else {
            wx.switchTab({
              url: "/pages/shop-manage/shop-manage",
              success: () => {
                console.log("跳转成功")
              },
              fail: (err) => {
                console.error("跳转失败:", err)
              },
            })
          }
        }
      })
      .catch((error) => {
        console.error("登录失败:", error)
        wx.showToast({
          title: "登录失败，请重试",
          icon: "none",
        })
      })
  },
})
